package main

import (
	"gdfs-center/conf"
	"gdfs-center/controller"
	"gdfs-center/db"
	"gdfs-center/engine"
	"gdfs-center/logcat"
	"gdfs-center/socket"
	"gdfs-center/utils"
	"github.com/gin-gonic/gin"
	"time"
)

var prefix = "/api"

func main() {
	//初始化配置读取工具
	config := conf.LoadConfig("")
	//初始化日志工具
	logcat.InitLogger(config.Viper.GetString("log.path"), "info")
	//初始化数据库
	db.InitDB(config)
	db.RunServerDB() //执行脚本
	conf.SetNetAddr(utils.GetInternetIp())
	StartTcpServer(config.GetEnvValue("tcptun.port"))
	//gin
	r := gin.Default()
	r.Use(LogerMiddleware())
	r.Use(gin.Recovery())
	api := r.Group("/gdfs", controller.JWTAuth) //中间件
	{
		//系统接口
		api.GET("/sys/userinfo", controller.GetUserInfo)                          //获取用户信息
		api.POST("/sys/login", controller.UserLogin)                              //登录接口
		api.POST("/sys/node/pagelist", controller.GetNodeList)                    //分页查询节点
		api.POST("/sys/node/add", controller.CreateNode)                          //创建节点
		api.POST("/sys/node/bind", controller.Bindnode)                           //绑定节点
		api.GET("/sys/node/nodenameidlist", controller.GetNodeIdAndNameList)      //获取节点名称和id列表
		api.GET("/sys/node/nodenamelist", controller.GetNodeNameList)             //获取节点名称列表
		api.POST("/sys/store/pagelist", controller.GetStoreList)                  //分页查询存储服务列表
		api.POST("/sys/store/remove", controller.RemoveStore)                     //删除存储服务
		api.POST("/sys/store/unbind", controller.UnBindNode)                      //解绑节点
		api.POST("/sys/store/createfulltask", controller.SyncfullData)            //全量同步接口
		api.POST("/sys/store/findstoreids", controller.FindStoreByNodeId)         //根据节点id查询存储服务id列表
		api.POST("/sys/store/sysinfo", controller.GetStoreSystemInfo)             //获取存储服务系统信息
		api.GET("/sys/store/options", controller.GetStorelistOption)              //获取store选项
		api.POST("/sys/syncdata/tasklist", controller.GetSyncTaskPageList)        //分页查询同步任务
		api.POST("/sys/syncdata/startfulltask", controller.StartSyncFullDataTask) //开始同步任务迁移数据
		api.POST("/sys/syncdata/stopfulltask", controller.StopSyncFullTask)       //停止全量同步
		api.POST("/sys/syncdata/removefulltask", controller.RemoveFullTask)       //删除全量同步任务
		api.GET("/sys/info", controller.GetSysteminfo)                            //获取系统数据
		//http转发
		api.POST(prefix+"/*name", controller.ProxyHttp)
		api.GET(prefix+"/*name", controller.ProxyHttp)
		api.PUT(prefix+"/*name", controller.ProxyHttp)
		api.DELETE(prefix+"/*name", controller.ProxyHttp)
		api.PATCH(prefix+"/*name", controller.ProxyHttp)
	}
	r.Run(":" + config.GetEnvValue("web.port"))

}

//启动Tcp通信
func StartTcpServer(tcptun string) {
	//Tcp
	s := socket.NewSocket()
	syschannel := s.MakeTcpChannel(tcptun, 6*1024*1024, 0, socket.ControllerHandler)
	s.BindServer(syschannel)
	s.ListenTcp()
	//心跳检查
	hearbeatCheck()
}

//服务端心跳检查
func hearbeatCheck() {
	timer := time.NewTicker(time.Second * 60)
	go func() {
		for {
			select {
			case <-timer.C:
				var hearts []db.HeartBeat
				db.GetDB().Find(&hearts)
				if len(hearts) > 0 {
					for _, h := range hearts {
						t := time.Now()
						if t.Sub(h.UpdatedAt).Seconds() > 35 {
							logcat.GetLog().Sugar().Info("###设备:", h.StoreId, "已离线---------!")
							if _, ok := engine.GetEngine().StoreMap[h.StoreId]; ok {
								s := engine.GetEngine().StoreMap[h.StoreId]
								s.SetAlive(false)
							}
						}
					}
				}
			}
		}
	}()
}

func LogerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//开始时间
		startTime := time.Now()
		//处理请求
		c.Next()
		//结束时间
		endTime := time.Now()
		// 执行时间
		latencyTime := endTime.Sub(startTime)
		//请求方式
		reqMethod := c.Request.Method
		//请求路由
		reqUrl := c.Request.RequestURI
		//状态码
		statusCode := c.Writer.Status()
		//请求ip
		clientIP := c.ClientIP()
		// 日志格式
		logcat.GetLog().Sugar().Infow("req请求参数", "status_code:", statusCode, "latency_time:", latencyTime, "client_ip:", clientIP, "req_method:", reqMethod, "req_uri", reqUrl)
	}
}
